package com.nwpu.coursesupport.service.imple;

import com.nwpu.coursesupport.criteria.*;
import com.nwpu.coursesupport.entity.*;
import com.nwpu.coursesupport.entity.bean.Files;
import com.nwpu.coursesupport.entity.bean.Files.FileItem;
import com.nwpu.coursesupport.entity.bean.JSONResult;
import com.nwpu.coursesupport.entity.bean.Response;
import com.nwpu.coursesupport.enumeration.RoleType;
import com.nwpu.coursesupport.enumeration.Status;
import com.nwpu.coursesupport.enumeration.TaskType;
import com.nwpu.coursesupport.exception.BatchScorePerformanceException;
import com.nwpu.coursesupport.exception.BatchTaskAssignmentException;
import com.nwpu.coursesupport.mapper.*;
import com.nwpu.coursesupport.pagination.PageBounds;
import com.nwpu.coursesupport.service.AbstractService;
import com.nwpu.coursesupport.service.param.IDListParam;
import com.nwpu.coursesupport.service.param.IDParam;
import com.nwpu.coursesupport.service.param.TaskServiceParam;
import com.nwpu.coursesupport.tool.ServiceUtil;
import com.nwpu.coursesupport.tool.UpdateUtil;
import com.nwpu.coursesupport.view.AskList;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

@Service
public class TaskService extends AbstractService {

    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private LessonMapper lessonMapper;
    @Autowired
    private ClassMapper classMapper;
    @Autowired
    private ClassStudentMapper classStudentMapper;
    @Autowired
    private TaskAssignmentMapper taskAssignmentMapper;
    @Autowired
    private ScorePerformanceMapper scorePerformanceMapper;
    @Autowired
    private ResourceMapper resourceMapper;

    protected static Logger logger = LoggerFactory.getLogger(TaskService.class);


//    public JSONResult detail(IDParam p) throws Exception {
//        JSONResult rst = new JSONResult();
//        rst.fail();
//        if (p == null || p.getId() <= 0) {
//            logger.error("参数有误");
//            rst.fail("参数有误");
//            return rst;
//        }
//
//        Task task = this.taskMapper.findById(p.getId());
//        task.setAnswerAttachment(ServiceUtil.DeserializeFiles(task.getAnswerAttachmentBytes()));
//        task.setAttachment(ServiceUtil.DeserializeFiles(task.getAttachmentBytes()));
//        rst.addData("task", task);
//        rst.addData("courseId", task.getCourseId());
//        rst.success();
//
//        return rst;
//    }

    public JSONResult detail(IDParam p) throws Exception {
        JSONResult rst = new JSONResult();
        rst.fail();
        if (p == null || p.getId() <= 0) {
            logger.error("参数有误");
            rst.fail("参数有误");
            return rst;
        }

        Task task = this.taskMapper.findById1(p.getId());

        task.setAnswerAttachment(ServiceUtil.DeserializeFiles(task.getAnswerAttachmentBytes()));
        task.setAttachment(ServiceUtil.DeserializeFiles(task.getAttachmentBytes()));

        TaskServiceParam.CreateParam param = new TaskServiceParam.CreateParam();
        BeanUtils.copyProperties(task, param);


        int taskId = task.getId();


        List<TaskScoreItemEntity> taskScoreItemEntities = taskScoreItemDao.findByTaskId(taskId);

        ArrayList<TaskServiceParam.CreateParam.ScoreItem> scoreItems = new ArrayList<>();
        for (TaskScoreItemEntity taskScoreItemEntity : taskScoreItemEntities) {
            TaskServiceParam.CreateParam.ScoreItem scoreItem = new TaskServiceParam.CreateParam.ScoreItem();
            scoreItem.setScoreItem(taskScoreItemEntity.getDescription());
            scoreItem.setWeight(taskScoreItemEntity.getFullMark());
            scoreItems.add(scoreItem);
        }
        param.setScoreItems(scoreItems);

        List<TaskCourseTargetEntity> taskCourseTargetEntities = taskCourseTargetDao.findByTaskId(taskId);
        ArrayList<TaskServiceParam.CreateParam.CourseTarget> courseTargets = new ArrayList<>();
        for (TaskCourseTargetEntity targetEntity : taskCourseTargetEntities) {
            TaskServiceParam.CreateParam.CourseTarget courseTarget = new TaskServiceParam.CreateParam.CourseTarget();
            courseTarget.setWeight(targetEntity.getWeight());
            courseTarget.setCourseTargetId(targetEntity.getCourseTargetId());

            courseTargets.add(courseTarget);
        }
        param.setCourseTargets(courseTargets);

        System.out.println("数据为:" + param);
        rst.addData("task", param);
        rst.addData("courseId", task.getCourseId());
        rst.success();

        return rst;
    }

    @Autowired
    private TaskCourseTargetDao taskCourseTargetDao;
    @Autowired
    private TaskScoreItemDao taskScoreItemDao;

    public JSONResult listData(TaskSearchCriteria sc) {
        JSONResult rst = new JSONResult();
        rst.fail();

        if (sc == null) {
            logger.error("参数有误");
            return rst.fail("参数有误");
        }

        if (sc.getPageNo() <= 0) {
            sc.setPageNo(1);
        }

        int pageSize = 15;
        int totalCount = this.taskMapper.count(sc);
        int pageCount = totalCount % pageSize > 0 ? totalCount / pageSize + 1 : totalCount / pageSize;
        if (sc.getPageNo() > pageCount) {
            sc.setPageNo(pageCount);
        }
        PageBounds page = new PageBounds();
        page.setNumber(sc.getPageNo());
        page.setSize(pageSize);

        List<Task> list = this.taskMapper.find(sc, page);
        if (list == null) {
            logger.error("数据查询失败");
            return rst.fail("数据查询失败");
        }

        rst.addData("courseId", sc.getCourseId());
        rst.addData("list", list);
        rst.addData("search", sc);
        rst.addData("type", sc.getType());
        rst.addData("pageNo", sc.getPageNo());
        rst.addData("allpages", pageCount);
        rst.success();
        return rst;
    }

    /*public JSONResult listData(TaskServiceParam.SearchParam p) throws Exception {
        JSONResult rst = new JSONResult();
        rst.fail();

        if (p == null) {
            return rst.fail("参数有误");
        }

        TaskSearchCriteria sc = p.getSearch();
        if (sc == null) {
            sc = new TaskSearchCriteria();
        }

        PageBounds page = new PageBounds();
        page.setNumber(1);
        page.setSize(10);

        List<Task> list = this.taskMapper.find(sc, page);
        if (list == null) {
            return rst.fail("数据查询失败");
        }

        rst.addData("list", list);
        rst.addData("search", sc);
        rst.addData("pageBounds", page);
        rst.success();
        return rst;
    }
*/
    public JSONResult createLessonTask(TaskServiceParam.CreateLessonTaskParam p) throws Exception {
        JSONResult rst = new JSONResult();
        rst.fail();

        if (p == null || p.getLessonId() <= 0 || p.getType() == null) {
            logger.error("参数有误");
            return rst.fail("参数有误");
        }

        //create task
        Task task = new Task();
        Lesson lesson = this.lessonMapper.findById(p.getLessonId());
        if (lesson == null) {
            logger.error("该课堂不存在");
            return rst.fail("该课堂不存在");
        }
        /*判断班级人数是否小于提问人数，如果小于则1）设置提问人数为班级人数-正常分配任务；2）返回提示-任务创建失败*
         *这里采取方案2
         */
        ClassStudentSearchCriteria csSearchCriteria = new ClassStudentSearchCriteria();
        csSearchCriteria.setClassId(lesson.getClassId());
        int numberOfClassStudent = this.classStudentMapper.countStudentByParam(csSearchCriteria);
        if (numberOfClassStudent < p.getNumsOfAnswerers()) {
            logger.error("提问人数超过班级人数");
            return rst.fail("提问人数太多! 该班学生人数为:" + numberOfClassStudent);
        }
        int id = (int) getSession().getAttribute("id");
        String name = (String) getSession().getAttribute("name");
        RoleType roleType = (RoleType) getSession().getAttribute("roleType");

        com.nwpu.coursesupport.entity.Class classes = this.classMapper.findById(lesson.getClassId());
        Course course = this.courseMapper.findById(classes.getCourseId());

        if (course.getTid() != id) {
            logger.error("你没有该权限");
            return rst.role("你没有权限");
        }
        Date date = new Date();
        task.setCourseId(course.getId());
        task.setCreateDate(date);

        task.setCreateId(id);
        task.setCreateName(name);
        task.setRoleType(roleType);
        task.setIsQuote(Status.NO);
        task.setDescription(p.getDescription());
        task.setTitle(p.getTitle());
        task.setType(p.getType());

        if (!this.taskMapper.save(task)) {
            logger.error("保存失败，并抛出异常BatchTaskAssignmentException");

            throw new BatchTaskAssignmentException("taskInLesson分派失败");
        }

        rst.addData("task", task);
        //assign task
        List<TaskAssignment> result = new ArrayList<TaskAssignment>();
        TaskAssignment assign = new TaskAssignment();
        assign.setTaskId(task.getId());
        assign.setLessonId(p.getLessonId());
        assign.setAssignDate(date);
        assign.setAssignId(id);
        assign.setAssignName(name);
        assign.setRoleType(roleType);
        assign.setClassName(lesson.getClassName());

        assign.setNumsOfAnswerers(p.getNumsOfAnswerers());

        if (p.getIsVisible() == null) {
            assign.setIsVisible(Status.NO);
        } else {
            assign.setIsVisible(p.getIsVisible());
        }

        if (p.getIsAnswerVisible() == null) {
            assign.setIsAnswerVisible(Status.NO);
        } else {
            assign.setIsAnswerVisible(p.getIsAnswerVisible());
        }
        result.add(assign);

        if (result.size() <= 0) {
            logger.error("result.size()<=0");
            return rst.fail("未分配成功！");
        }

        if (this.taskAssignmentMapper.batchSave(result) != result.size()) {
            logger.error("taskInLesson分派失败,并抛出异常BatchTaskAssignmentException");
            throw new BatchTaskAssignmentException("taskInLesson分派失败");
        }

        rst.addData("taskAssignmentId", result.get(0).getId());
        if (task.getIsQuote() != Status.YES) {
            task.setIsQuote(Status.YES);
            if (!this.taskMapper.updateQuote(task)) {
                logger.error("修改任务状态失败，并抛出异常BatchTaskAssignmentException");
                throw new BatchTaskAssignmentException("修改任务状态失败");
            }
        }
        //添加学生(result其实只有一个元素)
        for (int i = 0; i < result.size(); i++) {
            TaskAssignment item = result.get(i);
            if (!this.addScorePerformance(item, classes.getId())) {
                logger.error("TaskInlessonCreate 批量添加scorePerforce失败，并抛出异常BatchScorePerformanceException");
                throw new BatchScorePerformanceException();
            }
        }

        rst.success();

        return rst;
    }

    //TODO:solve later start 需要修改
    private boolean addScorePerformance(TaskAssignment assign, int classId) {
        List<AskList> list = genAskStudent(classId, assign.getNumsOfAnswerers());
        if (list.size() <= 0 || list.size() != assign.getNumsOfAnswerers()) {
            logger.error("error in addSccorePerformance" + assign.getNumsOfAnswerers());
            return false;
        }
        List<ScorePerformance> result = new ArrayList<ScorePerformance>();
        ScorePerformance item = null;
        for (AskList s : list) {
            item = new ScorePerformance();
            item.setAskStuId(s.getId());
            item.setAskStuName(s.getName());
            item.setAssignId(assign.getId());
            item.setIsScore(Status.NO);
            result.add(item);
        }
        if (this.scorePerformanceMapper.batchSave(result) != result.size()) {
            logger.error("scorePerformanceMapper.batchSave error");
            return false;
        }
        return true;
    }

    /**
     * 需要有一个比较公平的算法 进行生成待提问学生名单
     *
     * @return
     */
    private List<AskList> genAskStudent(int classId, int numbers) {
        List<Integer> studentIds = this.classMapper.findStudentByClassId(classId);
        if (studentIds.size() <= 0) {
            logger.error("studentIds.size()<=0");
            return new ArrayList<AskList>();
        }

        if (numbers > studentIds.size()) {//超过了所有学生的总和
            //logger.info("提问人数"+numbers+"学生人数"+studentIds.size());
            logger.error("提问人数" + numbers + "学生人数" + studentIds.size());
            return new ArrayList<AskList>();
        }

        AskListSearchCriteria sc = new AskListSearchCriteria();
        sc.setClassId(classId);
        sc.setIds(studentIds);
        List<AskList> list = this.scorePerformanceMapper.getAskRate(sc);
        if (list.size() <= 0) {
            return new ArrayList<AskList>();
        }
        //此时list的值从小到大排序
        int index = 0;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getTime() > list.get(0).getTime()) {
                break;
            }
            index++;
        }
        List<AskList> result = new ArrayList<AskList>();
        int flag = 0;
        if (index >= numbers) {
            flag = 0;
            Set<AskList> sets = new HashSet<AskList>(list.subList(0, index));
            for (AskList item : sets) {
                result.add(item);
                flag++;
                if (flag == numbers) {
                    break;
                }
            }
        } else {
            flag = 0;
            result.addAll(list.subList(0, index));
            Set<AskList> sets = new HashSet<AskList>(list.subList(index, list.size()));
            for (AskList item : sets) {
                result.add(item);
                flag++;
                if ((flag + index) == numbers) {
                    break;
                }
            }
        }

        return result;
    }

    //solve later end

    public JSONResult create(TaskServiceParam.CreateParam p) throws Exception {
        JSONResult rst = new JSONResult();
        rst.fail();

        if (p == null || p.getCourseId() <= 0 || p.getType() == null) {
            logger.error("参数有误");
            return rst.fail("参数有误");
        }

        Task task = p;
        Course course = this.courseMapper.findById(p.getCourseId());
        if (course == null) {
            logger.error("该课程不存在");
            return rst.fail("该课程不存在");
        }
        int id = (int) getSession().getAttribute("id");
        String name = (String) getSession().getAttribute("name");
        RoleType roleType = (RoleType) getSession().getAttribute("roleType");
        if (course.getTid() != id) {
            logger.error("你没有该权限");
            return rst.role("你没有该权限");
        }
        task.setAnswerAttachmentBytes(ServiceUtil.serializeFiles(task.getAnswerAttachment()));
        task.setAttachmentBytes(ServiceUtil.serializeFiles(task.getAttachment()));
        Date dd = new Date();
        task.setCreateDate(dd);
        task.setCreateId(id);
        task.setCreateName(name);
        task.setRoleType(roleType);
        task.setIsQuote(Status.NO);
        if (!this.taskMapper.save(task)) {
            logger.error("保存失败");
            return rst.fail("保存失败");
        }
        rst.addData("task", task);
        rst.success();
        return rst;
    }

    public JSONResult create1(TaskServiceParam.CreateParam p) throws Exception {
        JSONResult rst = new JSONResult();
        rst.fail();

        if (p == null || p.getCourseId() <= 0 || p.getType() == null) {
            logger.error("参数有误");
            return rst.fail("参数有误");
        }

        Task task = p;
        Course course = this.courseMapper.findById(p.getCourseId());
        if (course == null) {
            logger.error("该课程不存在");
            return rst.fail("该课程不存在");
        }
        int id = (int) getSession().getAttribute("id");
        String name = (String) getSession().getAttribute("name");
        RoleType roleType = (RoleType) getSession().getAttribute("roleType");
        if (course.getTid() != id) {
            logger.error("你没有该权限");
            return rst.role("你没有该权限");
        }
        task.setAnswerAttachmentBytes(ServiceUtil.serializeFiles(task.getAnswerAttachment()));
        task.setAttachmentBytes(ServiceUtil.serializeFiles(task.getAttachment()));
        Date dd = new Date();
        task.setCreateDate(dd);
        task.setCreateId(id);
        task.setCreateName(name);
        task.setRoleType(roleType);
        task.setIsQuote(Status.NO);
        if (!this.taskMapper.save(task)) {
            logger.error("保存失败");
            return rst.fail("保存失败");
        }
        //保存
        rst.addData("task", p);
        rst.success();
        int taskId = task.getId();

        DecimalFormat df = new DecimalFormat("#.00");

        //保存课程目标
        List<TaskServiceParam.CreateParam.CourseTarget> courseTargetsParam = p.getCourseTargets();
        BigDecimal totalWeight = new BigDecimal(0);
        for (TaskServiceParam.CreateParam.CourseTarget courseTarget : courseTargetsParam) {
            totalWeight = totalWeight.add(new BigDecimal(df.format(courseTarget.getWeight())));
        }
        if (totalWeight.compareTo(new BigDecimal(1)) != 0) {
            rst.fail("课程目标的权重和不为1");
            return rst;
        }
        for (TaskServiceParam.CreateParam.CourseTarget courseTarget : courseTargetsParam) {
            TaskCourseTargetEntity taskCourseTargetEntity = new TaskCourseTargetEntity();
            taskCourseTargetEntity.setFullMark((task.getFullMark() * courseTarget.getWeight()));
            taskCourseTargetEntity.setTaskId(taskId);
            taskCourseTargetEntity.setCourseTargetId(courseTarget.getCourseTargetId());
            taskCourseTargetEntity.setWeight(courseTarget.getWeight());
            taskCourseTargetDao.save(taskCourseTargetEntity);
        }

        //保存评分项
        if (!p.getIsSelect()) {
            BigDecimal fullMark = new BigDecimal(task.getFullMark());
            BigDecimal totalMark = new BigDecimal(0);
            List<TaskServiceParam.CreateParam.ScoreItem> scoreItemsParam = p.getScoreItems();
            for (TaskServiceParam.CreateParam.ScoreItem scoreItem : scoreItemsParam) {
                totalMark = totalMark.add(new BigDecimal(df.format(scoreItem.getWeight())));
            }
            if (totalMark.compareTo(fullMark) != 0) {
                rst.fail("评分项总分不等于满分");
                return rst;
            }
            for (TaskServiceParam.CreateParam.ScoreItem scoreItem : scoreItemsParam) {
                TaskScoreItemEntity taskScoreItemEntity = new TaskScoreItemEntity();
                taskScoreItemEntity.setTaskId(taskId);
                taskScoreItemEntity.setFullMark(scoreItem.getWeight());
                taskScoreItemEntity.setDescription(scoreItem.getScoreItem());
                taskScoreItemDao.save(taskScoreItemEntity);
            }
        }
        return rst;
    }


    public JSONResult update(TaskServiceParam.UpdateParam p) throws Exception {
        JSONResult rst = new JSONResult();
        rst.fail();

        if (p == null || p.getId() <= 0) {
            logger.error("参数有误");
            return rst.fail("参数有误");
        }

        Task task = this.taskMapper.findById(p.getId());
        if (task == null) {
            logger.error("记录不存在或已被删除");
            return rst.fail("记录不存在或已被删除");
        }

        if (UpdateUtil.setValues(task, p) > 0) {
//            System.out.println("task:::" + task);
            if (!this.taskMapper.update(task)) {
                logger.error("保存失败");
                return rst.fail("保存失败");
            }
        }

        rst.addData("task", task);
        rst.success();
        return rst;
    }

    public JSONResult update1(TaskServiceParam.CreateParam p) throws Exception {
        JSONResult rst = new JSONResult();
        rst.fail();

        if (p == null || p.getId() <= 0) {
            logger.error("参数有误");
            return rst.fail("参数有误");
        }

        Task task = this.taskMapper.findById(p.getId());
        if (task == null) {
            logger.error("记录不存在或已被删除");
            return rst.fail("记录不存在或已被删除");
        }

        if (UpdateUtil.setValues(task, p) > 0) {
            if (!this.taskMapper.update(task)) {
                logger.error("保存失败");
                return rst.fail("保存失败");
            }
        }
        rst.addData("task", p);
        rst.success();


        int taskId = task.getId();
        DecimalFormat df = new DecimalFormat("#.00");

        //删除课程目标，评分项
        List<TaskScoreItemEntity> scoreItemEntities = taskScoreItemDao.findByTaskId(taskId);
        if (!CollectionUtils.isEmpty(scoreItemEntities))
            for (TaskScoreItemEntity scoreItemEntity : scoreItemEntities) {
            taskScoreItemDao.deleteById(scoreItemEntity.getId());
        }
        List<TaskCourseTargetEntity> targetEntities = taskCourseTargetDao.findByTaskId(taskId);
        if (!CollectionUtils.isEmpty(targetEntities))
            for (TaskCourseTargetEntity targetEntity : targetEntities) {
            taskCourseTargetDao.deleteById(targetEntity.getId());
        }


        //保存课程目标
        List<TaskServiceParam.CreateParam.CourseTarget> courseTargetsParam = p.getCourseTargets();
        BigDecimal totalWeight = new BigDecimal(0);
        for (TaskServiceParam.CreateParam.CourseTarget courseTarget : courseTargetsParam) {
            totalWeight = totalWeight.add(new BigDecimal(df.format(courseTarget.getWeight())));
        }
        if (totalWeight.compareTo(new BigDecimal(1)) != 0) {
            rst.fail("课程目标的权重和不为1");
            return rst;
        }
        for (TaskServiceParam.CreateParam.CourseTarget courseTarget : courseTargetsParam) {
            TaskCourseTargetEntity taskCourseTargetEntity = new TaskCourseTargetEntity();
            taskCourseTargetEntity.setFullMark((task.getFullMark() * courseTarget.getWeight()));
            taskCourseTargetEntity.setTaskId(taskId);
            taskCourseTargetEntity.setCourseTargetId(courseTarget.getCourseTargetId());
            taskCourseTargetEntity.setWeight(courseTarget.getWeight());
            taskCourseTargetDao.save(taskCourseTargetEntity);
        }

        //保存评分项
        if (!p.getIsSelect()) {
            BigDecimal fullMark = new BigDecimal(task.getFullMark());
            BigDecimal totalMark = new BigDecimal(0);
            List<TaskServiceParam.CreateParam.ScoreItem> scoreItemsParam = p.getScoreItems();
            for (TaskServiceParam.CreateParam.ScoreItem scoreItem : scoreItemsParam) {
                totalMark = totalMark.add(new BigDecimal(df.format(scoreItem.getWeight())));
            }
            if (totalMark.compareTo(fullMark) != 0) {
                rst.fail("评分项总分不等于满分");
                return rst;
            }
            for (TaskServiceParam.CreateParam.ScoreItem scoreItem : scoreItemsParam) {
                TaskScoreItemEntity taskScoreItemEntity = new TaskScoreItemEntity();
                taskScoreItemEntity.setTaskId(taskId);
                taskScoreItemEntity.setFullMark(scoreItem.getWeight());
                taskScoreItemEntity.setDescription(scoreItem.getScoreItem());
                taskScoreItemDao.save(taskScoreItemEntity);
            }
        }
        return rst;
    }


    public JSONResult deleteAttachment(TaskServiceParam.DeleteAttachment p) throws Exception {
        JSONResult rst = new JSONResult();
        rst.fail();

        if (p == null || p.getId() <= 0) {
            logger.error("参数有误");
            return rst.fail("参数有误");
        }

        Task task = this.taskMapper.findById(p.getId());
        if (task == null) {
            logger.error("记录不存在或已被删除");
            return rst.fail("记录不存在或已被删除");
        }
        if (p.getType() == 1) {
            task.setAttachment(ServiceUtil.DeserializeFiles(task.getAttachmentBytes()));
            removeAttachment(p.getKey(), task.getAttachment());
            task.setAttachmentBytes(ServiceUtil.serializeFiles(task.getAttachment()));
            if (!this.taskMapper.updateAttachment(task)) {
                logger.error("修改失败");
                return rst.fail("修改失败");
            }
            rst.addData("attachments", task.getAttachment().getFiles());
        } else if (p.getType() == 2) {
            task.setAnswerAttachment(ServiceUtil.DeserializeFiles(task.getAnswerAttachmentBytes()));
            removeAttachment(p.getKey(), task.getAnswerAttachment());
            task.setAnswerAttachmentBytes(ServiceUtil.serializeFiles(task.getAnswerAttachment()));
            if (!this.taskMapper.updateAnswerAttachment(task)) {
                logger.error("修改失败");
                return rst.fail("修改失败");
            }
            rst.addData("attachments", task.getAnswerAttachment().getFiles());
        } else {
            logger.error("参数有误");
            return rst.fail("参数有误");
        }

        int id = (int) getSession().getAttribute("id");
        List<String> keys = new ArrayList<String>();
        keys.add(p.getKey());
        List<Resource> listR = this.resourceMapper.findByKeys(keys);
        List<Integer> list = new ArrayList<Integer>();
        for (int i = 0; i < listR.size(); i++) {
            if (listR.get(i).getUploadId() == id) {
                list.add(new Integer(listR.get(i).getId()));
            }
        }
        if (list.size() > 0) {
            if (!this.resourceMapper.batchDelete(list)) {
                logger.error("task-删除失败");
                rst.fail("t-删除失败");
                return rst;
            }
        }

        rst.success();
        return rst;
    }

    public JSONResult addAttachment(TaskServiceParam.AddAttachment p) throws Exception {
        JSONResult rst = new JSONResult();
        rst.fail();

        if (p == null || p.getId() <= 0) {
            logger.error("参数有误");
            return rst.fail("参数有误");
        }

        Task task = this.taskMapper.findById(p.getId());
        if (task == null) {
            logger.error("记录不存在或已被删除");
            return rst.fail("记录不存在或已被删除");
        }
        if (p.getType() == 1) {
            task.setAttachment(ServiceUtil.DeserializeFiles(task.getAttachmentBytes()));
            if (containAttachment(p.getKey(), task.getAttachment())) {
                logger.error("该文件已存在");
                return rst.fail("该文件已存在");
            }
            FileItem item = new FileItem();
            item.setName(p.getName());
            item.setUrl(p.getKey());
            if (task.getAttachment() == null) {
                task.setAttachment(new Files());
            }
            if (task.getAttachment().getFiles() == null) {
                task.getAttachment().setFiles(new ArrayList<FileItem>());
            }
            task.getAttachment().getFiles().add(item);
            task.setAttachmentBytes(ServiceUtil.serializeFiles(task.getAttachment()));
            if (!this.taskMapper.updateAttachment(task)) {
                logger.error("修改失败");
                return rst.fail("修改失败");
            }
            rst.addData("attachments", task.getAttachment().getFiles());
        } else if (p.getType() == 2) {
            task.setAnswerAttachment(ServiceUtil.DeserializeFiles(task.getAnswerAttachmentBytes()));
            if (containAttachment(p.getKey(), task.getAnswerAttachment())) {
                logger.error("该文件已存在");
                return rst.fail("该文件已存在");
            }
            FileItem item = new FileItem();
            item.setName(p.getName());
            item.setUrl(p.getKey());
            if (task.getAnswerAttachment() == null) {
                task.setAnswerAttachment(new Files());
            }
            if (task.getAnswerAttachment().getFiles() == null) {
                task.getAnswerAttachment().setFiles(new ArrayList<FileItem>());
            }
            task.getAnswerAttachment().getFiles().add(item);

            task.setAnswerAttachmentBytes(ServiceUtil.serializeFiles(task.getAnswerAttachment()));
            if (!this.taskMapper.updateAnswerAttachment(task)) {
                logger.error("修改失败");
                return rst.fail("修改失败");
            }
            rst.addData("attachments", task.getAnswerAttachment().getFiles());
        } else {
            logger.error("参数有误");
            return rst.fail("参数有误");
        }

        rst.success();
        return rst;
    }

    private void removeAttachment(String key, Files f) {
        if (f == null || f.getFiles() == null || f.getFiles().size() <= 0) {
            return;
        }
        Iterator<FileItem> itor = f.getFiles().iterator();
        FileItem item = null;
        while (itor.hasNext()) {
            item = itor.next();
            if (item.getUrl().equals(key)) {
                itor.remove();
            }
        }
    }

    private boolean containAttachment(String key, Files f) {
        if (f == null || f.getFiles() == null || f.getFiles().size() <= 0) {
            return false;
        }
        for (FileItem item : f.getFiles()) {
            if (item.getUrl().equals(key)) {
                return true;
            }
        }
        return false;
    }


    public JSONResult remove(IDParam p) throws Exception {
        JSONResult rst = new JSONResult();
        rst.fail();

        if (p == null || p.getId() <= 0) {
            logger.error("参数有误");
            rst.fail("参数有误");
            return rst;
        }

        Task task = this.taskMapper.findById(p.getId());
        if (task == null) {
            logger.error("记录不存在或已被删除");
            return rst.fail("记录不存在或已被删除");
        }

        if (!this.taskMapper.delete(p.getId())) {
            logger.error("删除失败");
            return rst.fail("删除失败");
        }
/**
 * 个人任务，直接删除提交
 */
        if (task.getType() == TaskType.PERSONALTASK) {
            TaskSubmitResultSearchCriteria taskSubmitResultSearchCriteria = new TaskSubmitResultSearchCriteria();
            taskSubmitResultSearchCriteria.setAssignId(task.getId());
            List<TaskSubmitResult> taskSubmitResults = taskSubmitResultMapper.find(taskSubmitResultSearchCriteria);
            for (TaskSubmitResult taskSubmitResult : taskSubmitResults) {
                taskSubmitResultMapper.delete(taskSubmitResult.getId());
            }
            rst.addData("task", task);
            rst.success();
            return rst;
        }

        TaskAssignmentSearchCriteria taskAssignmentSearchCriteria = new TaskAssignmentSearchCriteria();
        taskAssignmentSearchCriteria.setTaskId(p.getId());
        List<TaskAssignment> taskAssignments = taskAssignmentMapper.find(taskAssignmentSearchCriteria);

        //删除任务分配
        for (TaskAssignment taskAssignment : taskAssignments) {
            //删除课堂提问，提交表
            ScorePerformanceSearchCriteria scorePerformanceSearchCriteria = new ScorePerformanceSearchCriteria();
            scorePerformanceSearchCriteria.setAssignId(taskAssignment.getId());
            List<ScorePerformance> scorePerformances = scorePerformanceMapper.find(scorePerformanceSearchCriteria);
            for (ScorePerformance scorePerformance : scorePerformances) {
                scorePerformanceMapper.delete(scorePerformance.getId());
            }
            //删除任务提交表
            TaskSubmitResultSearchCriteria taskSubmitResultSearchCriteria = new TaskSubmitResultSearchCriteria();
            taskSubmitResultSearchCriteria.setAssignId(taskAssignment.getId());
            List<TaskSubmitResult> taskSubmitResults = taskSubmitResultMapper.find(taskSubmitResultSearchCriteria);
            for (TaskSubmitResult taskSubmitResult : taskSubmitResults) {
                taskSubmitResultMapper.delete(taskSubmitResult.getId());
            }


            //删除任务分配
            taskAssignmentMapper.delete(taskAssignment.getId());
        }
        rst.addData("task", task);
        rst.success();
        return rst;
    }

    @Autowired
    private TaskSubmitResultMapper taskSubmitResultMapper;

    public JSONResult removeAll(IDListParam p) throws Exception {
        JSONResult rst = new JSONResult();
        rst.fail();

        if (p == null || p.getIds() == null || p.getIds().isEmpty()) {
            logger.error("参数有误");
            rst.fail("参数有误");
            return rst;
        }

        this.taskMapper.batchDelete(p.getIds());

        rst.success();
        return rst;
    }

    public Response getTaskById(Integer taskId){
        Task task = taskMapper.findById1(taskId);
        return Response.ok(task);
    }
}
